﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Gasco.Business.Services;

public partial class Controls_city_index : System.Web.UI.UserControl
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            LoadCities(null, 1, true, gvCity.SortExpression, gvCity.SortDirection.ToString(), -1);
    }

    private void LoadCities(string keyword,int pageNumber,bool setPageCount ,string sortBy,string desc ,int countryId)
    {
        ViewState["CurrentPage"] = pageNumber;

        CityService cityService = new CityService();
        if (countryId == -1)
        {
            if (setPageCount) 
            gvCity.VirtualItemCount = cityService.CountGetAll();
            gvCity.DataSource = cityService.SearchCities(keyword, gvCity.PageSize, pageNumber, sortBy, desc);
        }
        else
        {
            if (setPageCount) 
                gvCity.VirtualItemCount = cityService.CountGetCitiesByCountry(countryId);
            gvCity.DataSource = cityService.SearchCitiesByCountry(keyword,gvCity.PageSize,pageNumber,sortBy,desc,countryId);
        }
            

        gvCity.DataBind();
    }

    protected void gvcity_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvCity.PageIndex = e.NewPageIndex;
        LoadCities(tbSearch.Text,e.NewPageIndex+1,false,gvCity.SortExpression,gvCity.SortExpression.ToString(),-1);
    }

    protected void gvcity_Deleting(object sender, GridViewDeleteEventArgs e)
    {
        object key = gvCity.DataKeys[e.RowIndex].Value;
        CityService cityService = new CityService();
        cityService.DeleteCity(cityService.GetCity(Convert.ToInt32(key)));
        LoadCities(tbSearch.Text,1,true,gvCity.SortExpression,gvCity.SortDirection.ToString(),-1);
    }

    protected void lbSearch_Click(object sender, EventArgs e)
    {
        LoadCities(tbSearch.Text, 1, true, gvCity.SortExpression, gvCity.SortDirection.ToString(), -1);
    }
    protected void gvCity_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["sort"] == null || ViewState["sort"].ToString() == "asc")
        {
            e.SortDirection = SortDirection.Descending;
            ViewState["sort"] = "desc";
        }
        else
        {
            e.SortDirection = SortDirection.Ascending;
            ViewState["sort"] = "asc";
        }
        LoadCities(tbSearch.Text, gvCity.PageIndex + 1, false, e.SortExpression, e.SortDirection.ToString(), -1);
    }

}
